import pymysql
import urllib.request
import json
from datetime import date, datetime, timedelta

db = pymysql.connect("114.115.160.16", "root", "123456Aa!", "fund")
cursor = db.cursor()

headers = {
    "token": "atTPd9c8sA"
}
sql = "select fund_id,category from api_fund"
cursor.execute(sql)
vary_id = 95966
for data in cursor.fetchall():
    fund_id = data[0]
    category = data[1]
    if category != 5:
        continue
            #sql = "insert into api_vary values(%d,'%s',%f,'%s','%s')" % (vary_id,fund_id,worth,date,rate)
    try:
        ###  vary
        response = urllib.request.urlopen(
            "https://api.doctorxiong.club/v1/fund/detail" + "?code=" + fund_id + "&startDate=" + "2021-04-15" + "&token=atTPd9c8sA").read().decode(
            "UTF-8")
        obj = json.loads(response)
        data = obj["data"]
        net_worth = data["millionCopiesIncomeData"]
        for single_data in net_worth:
            date = single_data[0]
            worth = float(single_data[1])
            rate = 0
            sql = "insert into api_vary values(%d,'%s',%f,'%s','%s')" % (vary_id,fund_id,worth,date,rate)
            cursor.execute(sql)
            #db.commit()
            vary_id += 1
        print("ok!", fund_id)
    except Exception as e:
        print(e)
        print("fail!", fund_id)
db.commit()